#! /usr/bin/env python
#coding=utf-8
import socket
from LinkSQL import LinkSQL, LogSQL
from JsonCode import JsonCode
from Ini2Dict import Ini2Dict
i = Ini2Dict()
ini = i.GetDict() 

class TellOther:
    
    def __init__(self):
        pass
        
    def TellSync(self):
        global ini
        sh = eval(ini["shost"])
        for s in sh:            
            HOST = s.split(":")[0]    # The remote host
            PORT = s.split(":")[1]              # The same port as used by the server
            try:                
                s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            except socket.error, msg:
                s = None
                continue
            try:                
                s.connect((HOST, int(PORT)))
            except socket.error, msg:
                s.close()
                s = None
                continue
            if s is not None:
                s.send('{"syncing":"1"}')
                #data = s.recv(1024)
                s.close()
            
    def GetSync(self, id):
        data = ''
        ajs = self.LoopID(id)
        while ajs != None:
            self.DoSQL(ajs['sql'])
            id = self.GetID()

            if ajs["id"] < id["id"]+1:
                ajs = self.LoopID(id)
            else:
                ajs = None
        
    def DoSQL(self, sub):
        
        sql = LinkSQL()

        try:
            sql.SQLQuery(sub)
            sql.Commit()
        except:
            sql.DBClose()
        import time, re 
        tn = time.strftime('%Y%U', time.localtime())
        sub = re.sub(r'\'', '\\\'', sub)
        lsql = "INSERT INTO `sql_log`.`sql_log_%s` (`sql`)VALUES ('%s');"%(tn, sub)

        sql.SQLQuery(lsql)
        sql.Commit()
        sql.DBClose()
        
    def LoopID(self, id):
        data = ''
        global ini        
        HOST = ini["mshost"]    # The remote host
        PORT = ini["msport"]              # The same port as used by the server
        try:            
            s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        except socket.error, msg:
            s = None
        try:
            if s is not None:

                s.connect((HOST, int(PORT)))
        except socket.error, msg:
            s.close()
            s = None
        if s is not None:
            sy = '{"sync":"%d"}'%int(id["id"])
            s.send(sy)
            while True:   
                receivedData = s.recv(1024)
                if not receivedData:   
                    break
                data += receivedData
            s.close()
            s = None
        ajs = None
        if len(data) > 0:
            js = JsonCode()
            ajs = js.DECode(data)
        return ajs
    
    def GetID(self):
        import time
        tn = time.strftime('%Y%U', time.localtime())
        sql = "SELECT `id` FROM `sql_log_%s` ORDER BY `id` DESC LIMIT 1"%tn
        
        db = LogSQL()
        db.SQLQuery(sql)
        id = db.GetOne()
        
        if id == None:
            id = {'id': '0'} 
        return id


